<?php
declare (strict_types=1);

namespace app\business\controller;

use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use app\common\model\ProductService;
use app\common\model\User;
use Qiniu\Auth;
use think\App;
use think\facade\View;
use app\common\model\ProductCate;
use app\common\model\Product as ProductModel;
use think\response\Json;
use app\common\model\Business;

class Product extends Base
{

    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Product';

    //验证器
    protected $validate = 'Product';

    //关联模型
    protected $hasOne = ['cate1', 'cate2', 'cate3'];

    protected $append = ['examineStatusText'];

    //待审核商品
    public function apply()
    {
        return $this->setTable(['business_id' => $this->business->id, 'examine_status'=>1, 'examine_del'=>0]);
    }

    //正式商品
    public function index()
    {
        return $this->setTable(['business_id' => $this->business->id, 'examine_status'=>2, 'is_del'=>0]);
    }

    public function setTable($map = [])
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'field' => '', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addRow(['field' => 'title', 'title' => '商品名称', 'width' => 200, 'fixed' => 'left'])
            ->addRow(['field' => 'icon', 'title' => '缩略图', 'width' => 90, 'templet' => '#iconTpl', 'fixed' => 'left'])
            ->addRow(['title'   => '商品分类', 'width' => 200,
                      'templet' => '<div>{{d.cate1.title}} - {{d.cate2.title}} - {{d.cate3.title}}</div>'])
            ->addRow(['field' => 'price', 'title' => '原价'])
            ->addRow(['field' => 'vip_price', 'title' => 'VIP价格'])
            ->addRow(['field' => 'freight', 'title' => '运费'])
            ->addRow(['field' => 'stock', 'title' => '库存'])
            ->addRow(['field' => 'create_time', 'title' => '添加时间', 'width' => 150])
            ->addRow(['field' => 'update_time', 'title' => '更新时间', 'width' => 150])
            ->addRow(['field' => 'examineStatusText', 'title' => '审核状态'])
            ->addRow(['fixed' => 'right', 'field' => 'sort', 'title' => '排序', 'width' => 120, 'templet' => '#sort_sort']);

        if($map['examine_status'] == 2){
            $tableFront->addRow(['fixed' => 'right', 'field' => 'status', 'title' => '上/下架', 'templet' => '#status', 'width' => 120])
                       ->addRow(['fixed' => 'right', 'field' => 'business_pick', 'title' => '店铺推荐', 'templet' => '#business_pick', 'width' => 120]);
        }

        $tableFront->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 150]);

        $topButtons = [];
        if($map['examine_status'] == 1){
            $topButtons = ['add' => ['width' => 1600, 'height' => 1200, 'title' => '新增']];
        }

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addTopButtons($topButtons)
            ->addRightButtons(['edit' => ['width' => 1600, 'height' => 1200, 'title' => '编辑'], 'delete'])
            ->addSwitchTool([['name' => 'status', 'pk' => 'id', 'text' => '上架|下架']])
            ->addSwitchTool([['name' => 'business_pick', 'pk' => 'id', 'text' => '开启|关闭']])
            ->setSearch($this->setSearch())
            ->addSortTool([['name' => 'sort', 'pk' => 'id', 'url' => url('update')->build()]])
            ->addExtraMap($map)
            ->addExtraHtml(['Product'])
            ->fetch();
    }

    public function setSearch()
    {
        $tableFront = TableFront::getInstance();
        $tableFront->setSearch(['title', '输入商品名称/描述', 'input', '', '', '', 'like'])
            ->setSearch(['cate_1', '商品专区', 'select', Business::getBusinessCart($this->business->cate_1)])
            ->setSearch(['status', '上架状态', 'select', ['1' => '上架', '2' => '下架']])
            ;
            //->setSearch(['examine_status', '审核状态', 'select', [1 => '待审核', 2 => '已通过', 3 => '已驳回']]);
        return $tableFront;
    }


    public function add($name = '', $tpl = 'product/edit')
    {
        $data = $this->assignData();
        View::assign($data);
        View::assign('info', null);
        return parent::add($name, $tpl);
    }

    public function edit($name = '', $id = '', $tpl = 'product/edit', $info = '')
    {
        $data = $this->assignData();
        $info = $this->model::find($id);
        $info->video_link_url = $info->video_link ? $data['domain'].$info->video_link : '';
        $info->content_videos_url = $info->content_videos ? $data['domain'].$info->content_videos : '';

        $info['service'] = $info['service'] ? explode(',', $info['service']) : '';
        $user = '';
        if($info->uid) $user = User::where('id', $info->uid)->value('concat_ws(" - ", nickname,code,mobile) as user');

        View::assign($data);
        View::assign('user', $user);
        return parent::edit($name, $id, $tpl, $info);
    }

    public function assignData()
    {
        $config = config('qiniu');
        // 构建鉴权对象
        $auth = new Auth($config['accessKey'], $config['secretKey']);
        $token = $auth->uploadToken($config['bucket']);

        return [
            'token' => $token,
            'domain' => $config['domain'],
            'cate' => Business::getBusinessCart($this->business->cate_1, 2),
            'service' => ProductService::where('is_del', 0)->select(),
        ];
    }


    public function getProduct()
    {
        try {
            $param = $this->request->get();
            $list = $this->model::whereLike('title', '%' . $param['val'] . '%')
                ->with(['business'])
                ->field('id,title,icon,business_id,price,vip_price')->select();
            return json(['code' => 0, 'data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function save($param = [], $model = true): Json
    {
        try{
            $param = $this->request->post();
            $this->validate($param, 'Product');
            $param['is_business'] = 1;
            return json($this->model::_saveSpec($param, $this->business, '已保存')); // TODO: Change the autogenerated stub
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function delete($key = 'is_del'): Json
    {
        $id = $this->request->post($this->pk);
        $examine_status = ProductModel::where('id', $id)->value('examine_status');
        $key = $examine_status == 2 ? 'is_del' : 'examine_del';
        return parent::delete($key); // TODO: Change the autogenerated stub
    }

    /**
     * 选择供应链会员
     * @return Json
     */
    public function selectUser(): Json
    {
        $param = $this->request->param();
        try{
            if ($this->request->isAjax()) {
                $user = User::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')->field('id,code,mobile,nickname')->where('is_del', 0)->select();
                return json(['code' => 0, 'data' => $user]);
            }
        }catch (\Exception $e){
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

}
